#!/usr/bin/python
import os
import sys
import subprocess

patchfile = sys.argv[1]
repopath = sys.argv[2]
alldifffiles = []
targetfiles = []

fp = open(patchfile, mode='r')
lines = fp.readlines()

def getprefix():
    for line in lines:
        if "diff --git" in line:
            originfile = line.split()[3].strip('b/')
            print(originfile)
            alldifffiles.append(originfile)

def get_otherrepo_path(repopath):
    for modifyfile in alldifffiles:
        basename = os.path.basename(modifyfile)
        #cmd = "cd %s"%repopath
        #os.system(cmd)
        cmd = "cd %s ; find -name %s"%(repopath,basename)
        print(cmd)
        result = subprocess.check_output([cmd], stderr=subprocess.STDOUT, shell=True)
        targetpath = result.decode("utf-8")
        targetfiles.append(targetpath)

def checktarget(line):
    for difffile in alldifffiles:
        if difffile in line:
            return True
    return False

def modifypatch():
    lena = len(alldifffiles)
    lenb = len(targetfiles)
    if lena == lenb:
        fp = open("new.patch", mode='w')
        for line in lines:
            if checktarget(line):
                print("need replace")
            else:
                fp.write(line)


getprefix()
get_otherrepo_path(repopath)
modifypatch()
